package com.rd.sys.common.utils.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 文件锁定操作工具类
 * 
 */
public class FileLockUtils {
    protected static final Logger logger = LoggerFactory.getLogger(FileLockUtils.class);

    public static void handlerByLockFile(File file, HandlerCaller hook) throws Exception {
        FileChannel channel = null;
        FileLock lock = null;
        try {
            /** 1.对该文件加锁(独占锁) */
            channel = new FileOutputStream(file).getChannel();
            while (true) {
                lock = channel.tryLock();// 独占锁
                if (lock == null) {
                    Thread.sleep(100);
                } else {
                    break;
                }
            }

            /** 2.执行函数 */
            hook.execute(channel);

        } catch (Exception ex) {
            logger.error("", ex);
            throw ex;
        } finally {
            if (lock != null) {
                try {
                    lock.release(); // 释放文件锁
                    lock = null;
                } catch (IOException ex) {
                    logger.error("release file lock error ", ex);
                }
            }
            if (channel != null) {
                try {
                    channel.close();
                    channel = null;
                } catch (IOException ex) {
                    logger.error("close file channel error ", ex);
                }
            }
        }
    }

}
